<?php

$db_obj = new db_obj();
$task_obj = new task_obj();
$client_obj = new client_obj();
$record_obj = new record_obj();
$expense_obj = new expense_obj();
$tariff_obj = new tariff_obj();

$periods = array();
for ($i = 2013; $i < date("Y") + 2; $i++) {
    for ($j = 1; $j < 13; $j++) {

        $temp = array(
            'period' => str_pad($j, 2, "0", STR_PAD_LEFT) . '/' . $i
        );

        $periods[] = $temp;
    }
}
$GLOBALS['template_data']['prefillPeriod'] = date("m/Y");
$GLOBALS['template_data']['periods'] = $periods;

if (!empty($_REQUEST['period'])) {

    $tasks = array();
    
    $GLOBALS['template_data']['prefillPeriod'] = $_REQUEST['period'];
    $period = explode("/", $_REQUEST['period']);
    
    $order1 = array(
        'col' => 'updated',
        'orderBy' => 'updated',
        'order' => 'ASC',
        'table' => '',
        'connector' => ''
    );

    $f1 = array(
        'status' => COMPLETED_TASK,
        'updated_month' => (int)$period[0],
        'updated_year' => $period[1]
    );
    $tasks1 = $task_obj->getListOfTasks($f1, $order1);
    foreach ($tasks1 as $task){
        $tasks[$task['taskId']] = $task;
    }
    
    $order2 = array(
        'col' => 'added',
        'orderBy' => 'added',
        'order' => 'ASC',
        'table' => '',
        'connector' => ''
    );

    $f2 = array(
        'status' => ACTIVE_TASK
    );
    $tasks2 = $task_obj->getListOfTasks($f2, $order2);
    foreach ($tasks2 as $key => $task){
        if ($key == 0)
            $task['break'] = 1;
        $tasks[$task['taskId']] = $task;
    }

// prechadzaju sa ulohy
    foreach ($tasks as $key => $task) {
        //ziskanie dat o klientovi z ulohy
        $client = $client_obj->getClient($task['client']);
        $tasks[$key]['client_info'] = $client;
        $tasks[$key]['added_formated'] = base_obj::convertDateTo($task['added'], "dd/mm/yyyy H:i:s", 'datetime');
        $tasks[$key]['updated_formated'] = base_obj::convertDateTo($task['updated'], "dd/mm/yyyy H:i:s", 'datetime');
        // zistenie poctu aktivnych mesiacov, napr ak uloha aktivna od 1.maja do 15.jula = 3
        $tasks[$key]['count_of_active_months'] = $task_obj->getCountOfActiveMonths($task['added'], $task['updated']);
        // vygenerovanie pola dvojic mesiac, rok - aktivne mesiace z Tasku
        $tasks[$key]['active_months_task'] = $task_obj->getArrayOfMonths($task['added'], $tasks[$key]['count_of_active_months']);
        // vygenerovanie pola dvojic mesiac, rok - aktivne mesiace z TSDR
        $tasks[$key]['active_months_records'] = $record_obj->getActiveMonths($task['taskId']);
        // zmergovanie mesiacov z tasku a z jeho TSDR
        $tasks[$key]['active_months'] = array_merge($tasks[$key]['active_months_task'], $tasks[$key]['active_months_records']);

        // ziskanie zucastnenych servisakov
        $filter = array(
            'taskId' => $task['taskId'],
            'nottariff' => 6,
            'nottype' => 8
        );
        $tasks[$key]['active_servismen'] = $record_obj->getListOfRecords($filter, array(), '', 'user_id', 'user_id'); // pole id servisakov
        $tasks[$key]['count_of_active_servismen'] = count($tasks[$key]['active_servismen']); // pocet servisakov
        // nastavenie vynosov a nakladov na 0
        $tasks[$key]['expense'] = 0; // naklad
        $tasks[$key]['revenue'] = 0; // vynos
        // prechadzam aktivne mesiace
        foreach ($tasks[$key]['active_months'] as $month) {

            //prechadzam servisakov
            foreach ($tasks[$key]['active_servismen'] as $servisman) {

                // zistenie fixnych nakladov daneho servisaka
                $fixed = $expense_obj->getExpenseInPeriodByUser($servisman['user_id'], ($month[1] . '-' . $month[0] . '-1'));
                // zistenie kolko casu bol servisak v danom mesiac na danej ulohe, okrem pravidelneho servisu
                $hours_on_task_per_servisman = $expense_obj->get_hours_per_servisman_on_task($servisman['user_id'], $month[0], $month[1], $task['taskId']);
                // zistenie kolko casu bol servisak v danom mesiac na vsetkych ulohach, okrem pravidelneho servisu
                $hours_per_servisman = $expense_obj->get_hours_per_servisman($servisman['user_id'], $month[0], $month[1]);
                // vypocet prvej casti nakladov: fixne naklady * cas na ulohe / celkovy cas
                if (!empty($hours_per_servisman)) {
                    $tasks[$key]['expense'] += ($fixed * $hours_on_task_per_servisman / $hours_per_servisman);
                }
            }

            // ak ma klient nastavenu zodpovednu osobu
            if (!empty($client['contactPerson'])) {
                // zistenie kolko casu bol zodpovedny na danej ulohe v danom mesiaci, okrem pravidelneho servisu
                $hours_on_task_per_responsible = $expense_obj->get_hours_per_responsible_on_task($task['taskId'], $client['klient_id'], $client['contactPerson'], $month[0], $month[1]);
                // zistenie kolko casu bol zodpovedny na ulohach pre daneho klienta v danom mesiaci, okrem pravidelneho servisu
                $hours_per_responsible = $expense_obj->get_hours_per_responsible($client['klient_id'], $client['contactPerson'], $month[0], $month[1]);

                // vypocet druhej casti nakladov: mesacna poplatok od klienta * cas zodpovedneho na ulohe / celkovy cas zodpovedneho na ulohach klienta
                if (!empty($hours_per_responsible)) {
                    $tasks[$key]['expense'] += ($client['monthlyFee'] * $hours_on_task_per_responsible / $hours_per_responsible);
                }
            }

            // znova prechadzam servisakov
            foreach ($tasks[$key]['active_servismen'] as $servisman) {
                // ziskanie TSDR zaznamov
                $records = $expense_obj->get_records_per_servisman_on_task($task['taskId'], $month[0], $month[1], $servisman['user_id'], true);

                // vypocet tretej casti nakladov: suma sucinov casu na ulohe a odmeny pre servisaka
                foreach ($records as $record) {
                    $servis_tariff = $tariff_obj->getTariffById($record['tariff'], array('servis_tariff'));
                    $tasks[$key]['expense'] += ($servis_tariff['servis_tariff'] * $record['amount']);
                }
            }

            // vynos z danej ulohy
            // vsetky TSDR
            $records = $expense_obj->get_records_per_servisman_on_task($task['taskId'], $month[0], $month[1]);

            //Suma sucinov zarobenej jednotkovej ceny a mnozstva
            foreach ($records as $record) {
                $tasks[$key]['revenue'] += ($record['unit_price'] * $record['amount']);
            }
        }
        // vypocet rentability
        if (!empty($tasks[$key]['expense']))
            $tasks[$key]['rentability'] = $tasks[$key]['revenue'] / $tasks[$key]['expense'];
        else
            $tasks[$key]['rentability'] = '-';
    }

    $GLOBALS['template_data']['tasks'] = $tasks;
}

?>
